package ca.tatham.senssim;

import java.util.LinkedList;
import java.util.List;

public class Link
{
  public static final List<Link> s_allLinks = new LinkedList<Link>();

  private final LinkedList<Node> m_nodes = new LinkedList<Node>();
  private LinkedList<Packet> m_nextTickPackets = new LinkedList<Packet>();
  private final String m_label;

  public Link(String label)
  {
    m_label = label;
    s_allLinks.add(this);
  }

  public List<Node> getNodes()
  {
    return m_nodes;
  }

  public void addNode(Node node)
  {
    if (node != null)
    {
      m_nodes.add(node);
      node.addLink(this);
    }
  }

  public synchronized final void tick()
  {
    for (Packet packet : getAndResetPackets())
    {
      for (Node node : m_nodes)
      {
        node.receivePacket(packet);
      }
    }
  }

  private List<Packet> getAndResetPackets()
  {
    List<Packet> packets = m_nextTickPackets;
    m_nextTickPackets = new LinkedList<Packet>();
    return packets;
  }

  /**
   * The packet will be received by all nodes on this Link in the next tick
   * cycle
   * 
   * @param packet
   */
  public void sendPacket(final Packet packet)
  {
    m_nextTickPackets.add(packet);
  }

  @Override
  public String toString()
  {
    StringBuilder msg = new StringBuilder();
    for (Node node : getNodes())
    {
      msg.append(node.toString() + ", ");
    }
    return "Link " + m_label + ": " + getNodes().size() + " nodes: " + msg;
  }
}
